package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink18_EventTime_Project {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.setParallelism(1);

        SingleOutputStreamOperator<String> mainStream = env
                .socketTextStream("hadoop162", 9999)
                .map(line -> {
                    String[] strings = line.split(",");
                    return new WaterSensor(strings[0], Long.valueOf(strings[1]), Integer.valueOf(strings[2]));
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                                .withTimestampAssigner((element, recordTimestamp) -> element.getTs())
                )
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private long timer;
                    boolean isFirst =true;
                    int lastVc = 0;

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {

                        String id = ctx.getCurrentKey();
                        System.out.println(timestamp);
                        out.collect("传感器:"+ id +"  水位上升超过5s，预警。。");

                    }
                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                        if (isFirst){ //第一条数据进来，注册定时器
                            isFirst = false;
                            timer = value.getTs() + 5000;
                            ctx.timerService().registerEventTimeTimer(timer);
                            System.out.println("第一条数据进来。。"+timer);

                        }else {
                            //判断相比上一条数据是否上升
                            Integer currentVc = value.getVc();
                            if (currentVc < lastVc){
                                ctx.timerService().deleteEventTimeTimer(timer);
                                timer = value.getTs() + 5000;
                                ctx.timerService().registerEventTimeTimer(timer);
                                System.out.println("重新触发。。"+timer);
                            }else {

                                System.out.println("定时器保持不变，水位上升");
                            }
                        }

                        //这次水位赋值给lastVc,等下次进来的就是上次了
                        lastVc = value.getVc();
                    }



                })
               ;
        mainStream.print("s1");
//        具有允许延迟3秒，同时水印必须要满足watermark =7000 ，查一秒都不行  同时还要大于水位大于20，才能触发预警

        //但是能重新输入sensor_1,1000,1 时间戳已经升上去了，存在逻辑错误！需要排除已经输入的状态的数据
        // 因此需要  加入状态的 数据！  这儿只能使用并行度为1 的情况
        env.execute();
    }
/*
*       flink 如何做到数据不丢失
*       1.事件时间 + 水印
*       2，允许迟到
*       3.侧输出流
* */
    /*
    * 第一条数据进来。。
        定时器保持不变，水位上升
        定时器保持不变，水位上升
        定时器保持不变，水位上升
        定时器保持不变，水位上升
        定时器保持不变，水位上升
        7000
        s1> 传感器:sensor_1  水位上升超过5s，预警。。
    * */


}
